<template>
  <div class="create-batch-container">
    <el-container class="layout-container">
      <el-aside width="220px" class="sidebar">
        <div class="sidebar-content">
          <el-button @click="goBack" class="back-btn">
            <el-icon><ArrowLeft /></el-icon>
            返回主页
          </el-button>
        </div>
      </el-aside>

      <el-main class="main-content">
        <div class="page-header">
          <h1>屠宰企业 - 创建产品批号</h1>
          <p>请填写产品批号相关信息</p>
        </div>

        <!-- 新建产品批号表单 -->
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><DocumentAdd /></el-icon>
              <span>新建产品批号</span>
            </div>
          </template>

          <el-form
            :model="form"
            :rules="rules"
            ref="formRef"
            label-width="200px"
            class="batch-form"
          >
            <!-- 1. 所属屠宰企业产品批号 -->
            <el-form-item label="所属屠宰企业产品批号：" prop="batchId">
              <el-input
                v-model="form.batchId"
                placeholder="请输入产品批号"
                @blur="checkBatchId"
                :class="{ 'error-border': batchIdExists }"
                class="form-input"
              />
              <div v-if="batchIdExists" class="error-text">
                <el-icon><Warning /></el-icon>
                该产品批号已存在
              </div>
            </el-form-item>

            <!-- 2. 所属屠宰企业编号 -->
            <el-form-item label="所属屠宰企业编号：" prop="slauId">
              <el-input
                v-model="form.slauId"
                placeholder="请输入屠宰企业编号"
                @blur="checkSlauId"
                :class="{ 'error-border': slauIdExists }"
                class="form-input"
              />
              <div v-if="slauIdExists" class="error-text">
                <el-icon><Warning /></el-icon>
                该屠宰企业编号不存在
              </div>
            </el-form-item>

            <!-- 3. 所属养殖企业进场编号 -->
            <el-form-item label="所属养殖企业进场编号：" prop="fbId">
              <el-select
                v-model="form.fbId"
                filterable
                placeholder="请选择养殖企业进场编号"
                class="form-input"
                @focus="loadFarmBatchList"
                @change="handleFarmBatchChange"
                :disabled="farmBatchLoading"
              >
                <el-option
                  v-for="batch in farmBatchList"
                  :key="batch.batch_id"
                  :label="batch.batch_id"
                  :value="batch.batch_id"
                />
              </el-select>
              <div v-if="farmBatchLoading" class="loading-text">
                <el-icon><Loading /></el-icon>
                加载中...
              </div>
            </el-form-item>

            <!-- 4. 产品品种 -->
            <el-form-item label="产品品种：" prop="type">
              <el-input
                v-model="form.type"
                placeholder="根据进场编号自动显示"
                class="form-input"
                :disabled="true"
              />
              <div v-if="productTypeLoading" class="loading-text">
                <el-icon><Loading /></el-icon>
                加载中...
              </div>
            </el-form-item>

            <!-- 5. 肉类检验检疫合格证编号 -->
            <el-form-item label="肉类检验检疫合格证编号：" prop="quaId">
              <el-input
                v-model="form.quaId"
                placeholder="请输入合格证编号"
                class="form-input"
              />
            </el-form-item>

            <!-- 6. 官方检验员名称 -->
            <el-form-item label="官方检验员名称：" prop="testName">
              <el-input
                v-model="form.testName"
                placeholder="请输入检验员名称"
                class="form-input"
              />
            </el-form-item>

            <!-- 7. 批号检验日期 -->
            <el-form-item label="批号检验日期：" prop="batchDate">
              <el-date-picker
                v-model="form.batchDate"
                type="date"
                placeholder="选择检验日期"
                class="form-input"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <!-- 8. 新建按钮 -->
            <el-form-item class="form-actions">
              <el-button
                type="primary"
                @click="submitForm"
                :loading="loading"
                class="submit-btn"
              >
                <el-icon><Check /></el-icon>
                新建产品批号
              </el-button>
              <el-button @click="resetForm" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button @click="goBack" class="cancel-btn">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { useTokenStore } from "@/stores/token.js";
import { useRouter } from "vue-router";
import {
  ArrowLeft,
  DocumentAdd,
  Warning,
  Loading,
  Check,
  Refresh,
  Close,
} from "@element-plus/icons-vue";

export default {
  name: "CreateSlauBatch",
  components: {
    ArrowLeft,
    DocumentAdd,
    Warning,
    Loading,
    Check,
    Refresh,
    Close,
  },
  setup() {
    const formRef = ref();
    const batchIdExists = ref(false);
    const slauIdExists = ref(false);
    const farmBatchList = ref([]);
    const farmBatchLoading = ref(false);
    const productTypeLoading = ref(false);
    const loading = ref(false);
    const tokenStore = useTokenStore();
    const router = useRouter();

    const form = reactive({
      batchId: "", // 所属屠宰企业产品批号
      slauId: "", // 所属屠宰企业编号
      fbId: "", // 所属养殖企业进场编号
      type: "", // 产品品种
      quaId: "", // 肉类检验检疫合格证编号
      testName: "", // 官方检验员名称
      batchDate: "", // 批号检验日期
    });

    // 验证屠宰企业编号
    const validateSlauId = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入屠宰企业编号"));
      } else {
        callback();
      }
    };

    const rules = {
      batchId: [
        { required: true, message: "请输入产品批号", trigger: "blur" },
        { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
      ],
      slauId: [
        { required: true, message: "请输入屠宰企业编号", trigger: "blur" },
        { validator: validateSlauId, trigger: "blur" },
      ],
      fbId: [
        {
          required: true,
          message: "请选择养殖企业进场编号",
          trigger: "change",
        },
      ],
      type: [{ required: true, message: "请选择产品品种", trigger: "change" }],
      quaId: [
        { required: true, message: "请输入合格证编号", trigger: "blur" },
        { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" },
      ],
      testName: [
        { required: true, message: "请输入检验员名称", trigger: "blur" },
        { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
      ],
      batchDate: [
        { required: true, message: "请选择检验日期", trigger: "change" },
      ],
    };

    // 获取 token
    const getToken = () => {
      return tokenStore.token;
    };

    // 带认证的请求函数
    const requestWithAuth = async (url, options = {}) => {
      const token = getToken();
      const headers = {
        "Content-Type": "application/json",
        ...options.headers,
      };

      if (token) {
        headers["Authorization"] = token;
      }

      const response = await fetch(url, {
        ...options,
        headers,
      });

      if (response.status === 401) {
        // Token 无效或过期，跳转到登录页
        ElMessage.error("登录已过期，请重新登录");
        tokenStore.removeToken();
        window.location.href = "/login";
        throw new Error("认证失败");
      } else if (response.status === 403) {
        // 权限不足
        ElMessage.error("权限不足，无法访问该资源");
        throw new Error("权限不足");
      } else if (!response.ok) {
        // 其他错误状态
        throw new Error(`HTTP错误! 状态码: ${response.status}`);
      }

      return response;
    };

    // 返回屠宰企业主页面
    const goBack = () => {
      router.push("/ent/slaghter");
    };

    // 检查产品批号是否已存在
    const checkBatchId = async () => {
      if (!form.batchId) return;

      try {
        const response = await requestWithAuth(
          `http://localhost:8080/api/slauBatch/checkBatchId?batchId=${form.batchId}`
        );
        const data = await response.json();
        batchIdExists.value = data.exists;
      } catch (error) {
        console.error("检查批号失败:", error);
        if (
          !error.message.includes("认证失败") &&
          !error.message.includes("权限不足")
        ) {
          ElMessage.error("检查批号失败");
        }
      }
    };

    // 检查屠宰企业编号是否存在
    const checkSlauId = async () => {
      if (!form.slauId) return;

      try {
        const response = await requestWithAuth(
          `http://localhost:8080/api/slauBatch/checkSlauId?slauId=${form.slauId}`
        );
        const data = await response.json();
        slauIdExists.value = !data.exists; // 如果不存在，设置为true显示错误
      } catch (error) {
        console.error("检查屠宰企业编号失败:", error);
        if (
          !error.message.includes("认证失败") &&
          !error.message.includes("权限不足")
        ) {
          ElMessage.error("检查屠宰企业编号失败");
        }
      }
    };

    // 加载养殖企业进场编号列表
    const loadFarmBatchList = async () => {
      if (farmBatchList.value.length > 0) return;

      farmBatchLoading.value = true;
      try {
        const response = await requestWithAuth(
          "http://localhost:8080/api/farmBatch/batchList"
        );

        const responseText = await response.text();

        if (!responseText.trim()) {
          throw new Error("服务器返回空响应");
        }

        let data;
        try {
          data = JSON.parse(responseText);
        } catch (parseError) {
          console.error("JSON解析错误:", parseError);
          throw new Error("服务器返回的数据格式不正确");
        }

        if (Array.isArray(data)) {
          farmBatchList.value = data;
          console.log("加载的养殖企业进场编号列表:", farmBatchList.value);
        } else {
          farmBatchList.value = [];
        }
      } catch (error) {
        console.error("加载养殖企业进场编号失败:", error);
        if (
          !error.message.includes("认证失败") &&
          !error.message.includes("权限不足")
        ) {
          ElMessage.error(`加载养殖企业进场编号失败: ${error.message}`);
        }
        farmBatchList.value = [];
      } finally {
        farmBatchLoading.value = false;
      }
    };

    // 处理进场编号选择变化
    const handleFarmBatchChange = async (batchId) => {
      console.log("选择的进场编号:", batchId);
      // 清空之前选择的产品品种
      form.type = "";

      // 根据进场编号加载产品品种
      if (batchId) {
        await loadProductTypeByBatchId(batchId);
      }
    };

    // 根据进场编号加载产品品种
    const loadProductTypeByBatchId = async (batchId) => {
      productTypeLoading.value = true;
      try {
        console.log("开始加载产品品种，batchId:", batchId);

        const response = await requestWithAuth(
          `http://localhost:8080/api/farmBatch/productTypeByBatchId?batchId=${batchId}`
        );

        console.log("产品品种接口响应状态:", response.status);

        if (response.ok) {
          const productType = await response.text();
          console.log("产品品种接口返回数据:", productType);

          if (productType && productType.trim() !== "") {
            form.type = productType.trim();
          } else {
            ElMessage.warning("该进场编号暂无产品品种数据");
            form.type = "";
          }
        } else {
          throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
      } catch (error) {
        console.error("加载产品品种失败:", error);
        ElMessage.error("加载产品品种失败");
        form.type = "";
      } finally {
        productTypeLoading.value = false;
      }
    };

    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return;

      try {
        const valid = await formRef.value.validate();
        if (!valid) {
          ElMessage.error("请完善表单信息");
          return;
        }

        if (batchIdExists.value) {
          ElMessage.error("产品批号已存在，请修改");
          return;
        }

        if (slauIdExists.value) {
          ElMessage.error("屠宰企业编号不存在，请修改");
          return;
        }

        loading.value = true;

        // 准备提交数据 - 严格按照数据库表结构
        const submitData = {
          batchId: form.batchId, // slau_batch.batch_id
          slauId: form.slauId, // slau_batch.slau_id
          fbId: form.fbId, // slau_batch.fb_id
          type: form.type, // slau_batch.type
          quaId: form.quaId, // slau_batch.qua_id
          testName: form.testName, // slau_batch.test_name
          batchDate: form.batchDate, // slau_batch.batch_date
        };

        // 调用后端创建接口
        const response = await requestWithAuth(
          "http://localhost:8080/api/slauBatch/create",
          {
            method: "POST",
            body: JSON.stringify(submitData),
          }
        );

        const result = await response.json();

        if (result.success) {
          ElMessage.success("产品批号创建成功");
          resetForm();
          // 提交成功后返回到屠宰企业主页面
          router.push("/ent/slaghter");
        } else {
          ElMessage.error(result.message || "创建失败");
        }
      } catch (error) {
        console.error("提交表单失败:", error);
        if (
          !error.message.includes("认证失败") &&
          !error.message.includes("权限不足")
        ) {
          ElMessage.error("提交表单失败");
        }
      } finally {
        loading.value = false;
      }
    };

    // 重置表单
    const resetForm = () => {
      if (formRef.value) {
        formRef.value.resetFields();
      }
      batchIdExists.value = false;
      slauIdExists.value = false;
      farmBatchList.value = [];
      farmBatchLoading.value = false;
      productTypeLoading.value = false;
      // 重置表单数据
      Object.keys(form).forEach((key) => {
        form[key] = "";
      });
    };

    return {
      formRef,
      form,
      rules,
      batchIdExists,
      slauIdExists,
      farmBatchList,
      farmBatchLoading,
      productTypeLoading,
      loading,
      checkBatchId,
      checkSlauId,
      loadFarmBatchList,
      handleFarmBatchChange,
      loadProductTypeByBatchId,
      submitForm,
      resetForm,
      goBack,
    };
  },
};
</script>

<style scoped>
.create-batch-container {
  height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.layout-container {
  height: 100%;
}

.sidebar {
  background: linear-gradient(180deg, #2d3748 0%, #1a202c 100%);
  padding: 20px;
  display: flex;
  align-items: flex-start;
}

.sidebar-content {
  width: 100%;
}

.back-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.back-btn .el-icon {
  margin-right: 8px;
}

.main-content {
  padding: 30px;
  background: transparent;
  overflow-y: auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #2d3748;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #718096;
  font-size: 16px;
}

.form-card {
  max-width: 800px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
}

.card-header .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.batch-form {
  padding: 10px 0;
}

.form-input {
  width: 300px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #4a5568;
}

.form-actions {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
}

.submit-btn,
.reset-btn,
.cancel-btn {
  border-radius: 8px;
  height: 40px;
  padding: 0 20px;
  transition: all 0.3s ease;
}

.submit-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.reset-btn:hover,
.cancel-btn:hover {
  transform: translateY(-1px);
}

.submit-btn .el-icon,
.reset-btn .el-icon,
.cancel-btn .el-icon {
  margin-right: 6px;
}

.error-border {
  border-color: #f56565;
}

.error-text {
  color: #f56565;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.error-text .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.loading-text {
  color: #4299e1;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.loading-text .el-icon {
  margin-right: 4px;
  font-size: 14px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .sidebar {
    width: 100% !important;
    height: auto;
  }

  .main-content {
    padding: 20px;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .form-input {
    width: 100%;
  }

  :deep(.el-form-item__label) {
    width: 100% !important;
  }
}
</style>
